/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ExportSql.java
 *
 * Created on 2011-6-24, 10:23:38
 */
package exportsql;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.ext.oracle.Oracle10DataTypeFactory;
import org.dbunit.operation.DatabaseOperation;

/**
 *
 * @author feng
 */
public class ExportSql extends javax.swing.JFrame {

    /** Creates new form ExportSql */
    public ExportSql() {
        initComponents();
        
        dbSetting = new Properties();
        String path = System.getProperty("user.dir");
        File file = new File(path + "/db.properties");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            dbSetting.load(new FileReader(file));
            String allname = dbSetting.getProperty("allname");
            List<String> nameList = new ArrayList<String>();
            for (String string : allname.split(",")) {
                if(string != null && string.trim().length() != 0){
                    nameList.add(string);
                }
            }
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(nameList.toArray(new String[nameList.size()])));
        } catch (IOException ex) {
            Logger.getLogger(ExportSql.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
        
        try {
            String[] ips = Utils.getLocalIp();
            for (String ip : ips) {
                System.out.println(ip);
                if(ip.equals("10.0.26.163")){
                    btnImportSqlToDb.setEnabled(false);
                    btnImportToDb.setEnabled(false);
                    break;
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(ExportSql.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    public void loadSetting(){
        
    }

    private IDatabaseConnection getDatabaseConnection(String configName) throws DatabaseUnitException, ClassNotFoundException, SQLException {
        String ip = dbSetting.getProperty(configName+".ip");
        String dbname = dbSetting.getProperty(configName+".dbname");
        String user = dbSetting.getProperty(configName+".user");
        String password = dbSetting.getProperty(configName+".password");
        String schema = dbSetting.getProperty(configName+".schema");

        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection jdbcConnection = DriverManager.getConnection(
                "jdbc:oracle:thin:@"+ip+":1521:"+dbname, user, password);
        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection,schema.toUpperCase());
        DatabaseConfig config = connection.getConfig();
        config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new Oracle10DataTypeFactory());
        config.setProperty(DatabaseConfig.FEATURE_SKIP_ORACLE_RECYCLEBIN_TABLES, true);
        //config.setProperty(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);
        return connection;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblSql = new javax.swing.JTable();
        btnImportSQL = new javax.swing.JButton();
        btnExportSqlFile = new javax.swing.JButton();
        btnImportSqlToDb = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtFileChoose = new javax.swing.JTextField();
        btnFileChoose = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtSql = new javax.swing.JTextArea();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        btnDbSetting = new javax.swing.JButton();
        btnImportToDb = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tblSql.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null}
            },
            new String [] {
                "表名", "SQL"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tblSql.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tblSql);

        btnImportSQL.setText("导入SQL");
        btnImportSQL.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportSQLActionPerformed(evt);
            }
        });

        btnExportSqlFile.setText("导出SQL文件");
        btnExportSqlFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportSqlFileActionPerformed(evt);
            }
        });

        btnImportSqlToDb.setText("导入SQL文件到数据库");

        jLabel1.setText("文件");

        txtFileChoose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtFileChooseActionPerformed(evt);
            }
        });

        btnFileChoose.setText("...");
        btnFileChoose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFileChooseActionPerformed(evt);
            }
        });

        txtSql.setColumns(20);
        txtSql.setRows(5);
        jScrollPane2.setViewportView(txtSql);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel2.setText("数据库");

        btnDbSetting.setText("数据库设置");
        btnDbSetting.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDbSettingActionPerformed(evt);
            }
        });

        btnImportToDb.setText("导入数据库");
        btnImportToDb.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportToDbActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 692, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtFileChoose, javax.swing.GroupLayout.PREFERRED_SIZE, 432, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnFileChoose, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnImportToDb, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnExportSqlFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnImportSQL, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnDbSetting)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnImportSqlToDb)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnImportSQL)
                        .addGap(40, 40, 40)
                        .addComponent(jScrollPane2))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnFileChoose)
                        .addComponent(btnImportSqlToDb)
                        .addComponent(btnExportSqlFile)
                        .addComponent(btnDbSetting))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txtFileChoose, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addComponent(btnImportToDb))
                .addContainerGap())
        );

        btnImportSQL.getAccessibleContext().setAccessibleName("");
        btnExportSqlFile.getAccessibleContext().setAccessibleName("");
        btnImportSqlToDb.getAccessibleContext().setAccessibleName("");
        btnFileChoose.getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtFileChooseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFileChooseActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtFileChooseActionPerformed

    private void btnFileChooseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFileChooseActionPerformed
        // TODO add your handling code here:
        String initPath = "c:";
        File file = new File(txtFileChoose.getText());
        if(file.exists()){
            initPath = file.getPath();
        }
        JFileChooser chooser = new JFileChooser(initPath);
        chooser.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                return f.isDirectory() || f.isFile() && f.getName().contains(".xml");
            }

            @Override
            public String getDescription() {
                return ".xml";
            }
        });
        int result = chooser.showSaveDialog(this);
        if(result == JFileChooser.APPROVE_OPTION){
            file = chooser.getSelectedFile();
            txtFileChoose.setText(file.getAbsolutePath());
        }
    }//GEN-LAST:event_btnFileChooseActionPerformed

    public void exportSqlToFile(String configName,File file,String[][] sqls) throws Exception{
        IDatabaseConnection connection = getDatabaseConnection(configName);
        // partial database export
        QueryDataSet partialDataSet = new QueryDataSet(connection);
        for (String[] rows : sqls) {
            partialDataSet.addTable(rows[0], rows[1]);
        }
        FlatXmlDataSet.write(partialDataSet, new FileOutputStream(file));        
    }
    
  
    
    private void btnImportSQLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImportSQLActionPerformed
        // TODO add your handling code here:
        String sqlAll = txtSql.getText();
        String[] sqls = sqlAll.split(";");
        TableModel model = new DefaultTableModel(new String[]{"表名","SQL"}, sqls.length);
        
        for(int i=0;i< sqls.length;i++){
            String s = sqls[i];
            if(s == null || "".equals(s.trim()))
                continue;
            String tableName = getTableName(s);
            
            model.setValueAt(tableName.toUpperCase(), i, 0);
            model.setValueAt(s, i, 1);
        }
        tblSql.setModel(model);
    }//GEN-LAST:event_btnImportSQLActionPerformed

    private void btnExportSqlFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportSqlFileActionPerformed
        // TODO add your handling code here:
        String configName = (String)jComboBox1.getSelectedItem();
        
        TableModel model = tblSql.getModel();
        String[][] data = new String[model.getRowCount()][];
        for (int i=0;i< model.getRowCount();i++) {
            data[i] = new String[2];
            data[i][0] = (String)model.getValueAt(i, 0);
            data[i][1] = (String)model.getValueAt(i, 1);
        }
        try {
            File file = new File(txtFileChoose.getText());
            exportSqlToFile(configName, file, data);
            JOptionPane.showMessageDialog(this, "导出完成！");
        } catch (Exception ex) {
            Logger.getLogger(ExportSql.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnExportSqlFileActionPerformed

    private void btnDbSettingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDbSettingActionPerformed
        // TODO add your handling code here:
        DbSettingDialog dialog = new DbSettingDialog(this, true);
        dialog.setVisible(true);
    }//GEN-LAST:event_btnDbSettingActionPerformed

    private void btnImportToDbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImportToDbActionPerformed
        // TODO add your handling code here:
        File file = new File(txtFileChoose.getText());
        String configName = (String)jComboBox1.getSelectedItem();
        InputStream is = null;
        String ip = dbSetting.getProperty(configName+".ip");
        if(ip.trim().startsWith("10.0.11")){
            JOptionPane.showMessageDialog(this, "不能往"+ip+"的数据库导入数据！");
            return;
        }
        try {
            IDatabaseConnection connection = getDatabaseConnection(configName);
            FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
            builder.setColumnSensing(true);
            is = new BufferedInputStream(new FileInputStream(file));
            IDataSet dataSet =  builder.build(is);
            DatabaseOperation.INSERT.execute(connection, dataSet);
            JOptionPane.showMessageDialog(this, "导入完成！");
        } catch (Exception ex) {
            Logger.getLogger(ExportSql.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException ex) {
                    Logger.getLogger(ExportSql.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_btnImportToDbActionPerformed

    public String getTableName(String sql){
        String KEYWORD_FROM = "from";
        String tmpSql = sql.toLowerCase();
        StringTokenizer token = new StringTokenizer(tmpSql);
        String ret = "";
        boolean find = false;
        while(token.hasMoreTokens()){
            String s = token.nextToken();
            if(find){
                ret = s;
                break;
            }
            if(s.equals(KEYWORD_FROM)){
                find = true;
            }
        }
        if(ret.contains("@")){
            ret = ret.substring(0,ret.indexOf("@"));
        }
        return ret;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ExportSql().setVisible(true);
            }
        });
    }
    
    public Properties getDbSetting(){
        return dbSetting;
    }
    
    private Properties dbSetting;
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDbSetting;
    private javax.swing.JButton btnExportSqlFile;
    private javax.swing.JButton btnFileChoose;
    private javax.swing.JButton btnImportSQL;
    private javax.swing.JButton btnImportSqlToDb;
    private javax.swing.JButton btnImportToDb;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tblSql;
    private javax.swing.JTextField txtFileChoose;
    private javax.swing.JTextArea txtSql;
    // End of variables declaration//GEN-END:variables
}
